package state_service

import (
	"go-blockchain-from-scratch/constants"
	"go-blockchain-from-scratch/database"
	"go-blockchain-from-scratch/mapper"
	"go.mongodb.org/mongo-driver/bson"
)

func UpdateOrSaveState(Name database.Account, value int, tx database.Tx) {
	filter := bson.M{"account": Name}
	state := new(database.State)
	err := mapper.SelectOne(constants.DataBase, constants.StateCollection, filter, state)
	if err != nil {
		//插入
		state.Name = tx.To
		state.Balances = uint(value)
		mapper.InsertOne(constants.DataBase, constants.StateCollection, state)
		return
	}
	//更新
	update := bson.D{{"$set", bson.D{{"balances", int(state.Balances) + value}}}}
	mapper.Update(constants.DataBase, constants.StateCollection, filter, update)

}
